﻿package com.cilico.single.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.R;
import com.cilico.single.components.Component;
import com.cilico.single.components.Component.SelfLayout;
import com.cilico.single.components.ComponentListener;
import com.cilico.single.components.CssStyle;
import com.cilico.single.components.Div;
import com.cilico.single.components.Label;
import com.cilico.single.components.Panel;
import com.cilico.single.components.ProgressDialog;
import com.cilico.single.components.Radio;
import com.cilico.single.components.RowPanel;
import com.cilico.single.components.Select;
import com.cilico.single.components.Select.SelectView;
import com.cilico.single.components.StatusBar;
import com.cilico.single.components.TabBar;
import com.cilico.single.components.TabBar.ContentLayout;
import com.cilico.single.components.Table;
import com.cilico.single.components.Table.Cell;
import com.cilico.single.components.TitleBar;
import com.cilico.single.components.WaitDialog.Task;
import com.cilico.single.components.Wrap;
import com.cilico.single.components.mViewFlipper;
import com.cilico.single.utils.StringTicker;
import com.cilico.single.utils.Utils;

public class BaseView extends Activity {
	//保存所有存活的activity
	public static ArrayList<Activity> activities_;
    // activity是否改变标志，当程序运行在前台时始终为假
    static boolean CHANGEWORKED;
    // 程序转到后台前存储的类名
    static String HIDESCREEN;
    // 代码执行标记
    static boolean ISHADACT;
    public static Mid mid_;
    public ComponentListener listener_;
    boolean coveExist_;
    
    Component partScreenWait_;
    ImageView ivBackground_;
    Bitmap ivLoginViewBackgroundBitmap_;
    static Bitmap ivMainViewAndDetailViewBackgroundBitmap_;
    
    static String[] labels_ = null;
	static Bitmap[] bitmaps_ = null;
	static Bitmap[] bitmapsD_ = null;
    static String[] labels_1 = null;
	static Bitmap[] bitmaps_1 = null;
	static Bitmap[] bitmapsD_1 = null;
	public static Bitmap[] arrowIcons_ = null;
	static Bitmap[] mainMenuMap_ = null;
    // indicate a view need scrollbar or not. default value is true.
    boolean isNeedScrollBar_ = true;
    protected boolean showTab_; // indicate showing tab or not.
    // This is for form action
    Vector<FormAction> formV_;

    protected static final int DRAW_MODE_MAP = 1;

    public int blackView_ = 0; // 0 indicate 'yes', 1 means 'no', 2 means 'clear', 3 means 'refresh'.

    /* indicators for ceair cjr & lxr editing. */
    public boolean isInCeAirCjrLxrDiv_;

    public static final int DEFAULT_PAINT_SIZE = 20;
    /** Currently active menu. , the subclass shout not call it directly */
    // static final String TEXT_INPUT = "点击这里输入...";
    public static final int SCROLL_BAR_WIDTH = 5;
    public static final int SCROLL_BAR_RIGHT_MARGIN = 2;
    public static final int SCROLL_BAR_AREA_WIDTH = 7; // the whole width of the scroll bar area.
    public static final int LAST_ITEM_BOTTOM_MARGIN = 2;
    public static final int FIRST_ITEM_TOP_MARGIN = 6; // MUST == SCROLL_BAR_TOP_MARGIN
    public static final int ITEM_MARGIN = 2;
    public static final int HL_SEGMENTRADIO = 0xFF003380;
    public static final int UN_SEGMENTRADIO = 0xFF5E5F5E;
    public static final int HL_BACKGROUND_COLOR = 0xFF2874DC;
    public static final int HL_TABBAR_COLOR = 0xFF405F87;
    public static final int STATUS_BAR_COLOR = 0x008F8E88;
    public static final int HL_FOREGROUND_COLOR = Utils.WHITE;
    public static final int BACKGROUND_COLOR = Utils.WHITE;
    public static final int FOREGROUND_COLOR = 0xFFFFFFFF;
    public static final int HYPERLINK_UNDERLINE_COLOR = 0x808080;
    public static final int SCROLL_BAR_BACKGROUND = 0x00C5C7C9;
    public static final int SCROLL_BAR_FOREGROUND = 0x00808588;
    public static final int ITEM_BACKGROUND_GREY = 0xd4d4d4;
    public static final int COLOR_BUTTONTEXT = 0xFF000000;
    /** This selects which menu we display. */
    protected int rightMenuMode_;
    public static String rightMenuText_;
    public final static int OPTIONS_MENU = 1;
    public final static int OTHER_MENU = 2;
    private int leftMenuMode_;
    final static int BACK_MENU = 3;
    public static String leftMenuText_;
    public final static int EXIT_MENU = 4;
    public final static int NO_MENU = 5;
    public static final int MENUBAR_TOP_MARGIN = 2;
    public static final int MENUBAR_LEFT_MARGIN = 4;
    public static final int ITEM_LEFT_MARGIN = 7;
    public static final int Y_MARGIN = 4;
    public static final int X_MARGIN = 4;

    public static final int MAX_WIDTH = Utils.screenWidth_ - BaseView.SCROLL_BAR_AREA_WIDTH - BaseView.SCROLL_BAR_RIGHT_MARGIN - BaseView.ITEM_LEFT_MARGIN - BaseView.X_MARGIN * 2;
    /*
     * When scrolling, we translate the list of all items by their Y coordinates. During each scroll, we move up/down by
     * the height of current item, or scrollUnit_ pixels, whichever smaller. This is done by moving virtual pointer
     * CURRENT. We then draw all items that fall within the current viewport, and ignore items that are beyond.
     * 
     * ITEMTOP: offset of the top of the currently active item. CURRENT: offset of the current virtual pointer. We move
     * this pointer at most scrollUnit_ pixels at a time. TOP and BOTTOM are bounds of the current viewport, they are
     * relative to the left/top of the FULL canvas. HEIGHT: BOTTOM - TOP.
     */
    protected final static int TOP = 0;
    protected final static int BOTTOM = 1;
    protected final static int HEIGHT = 2;
    protected final static int VIEW_LEFT = 3;
    protected final static int VIEW_RIGHT = 4;
    protected final static int WIDTH = 5;
    protected int[] viewport_;
    /** Unit when we scroll up or down */
    final int scrollUnit_ = 18;

    /** Item to be highlighted. */
    public int currentItem_;

    /** Total height of all items, for scrolling. */
    int itemStartH_;
    int itemEndH_;
    protected int totalItemHeight_;
    protected int totalItemWidth_;

    boolean showVerticalScrollBar_;
    boolean showBackGround_;
    // 是否需要标题头标志位（该标题头之界面最上方标题栏控件）
    boolean isNeedTitleBar_;
    static long beginTime_;
    static final int INTERVAL = 200;
    // Default top margin of views.
    public static final int DEFAULT_VIEW_TOP_MARGIN = 10;
    protected int BackGroundColor_;
    // 菜单组序号
    int idGroup_;
    // 菜单序号
    int idItem_;
    // 菜单命令名值对应表，用户处理源程序的菜单命令名和id的对应关系
    public Hashtable<String, String> hashMenu_;
    // 日期控件标记名
    public String viewDateFieldTag_;

    public Label countLabel_;
    public Timer countTimer_;
    public Timer exitAppTimer_;
    // 该管理器为界面最上层管理器，只为添加背景图片应用。子视图包括背景图片和llScreen_
    public FrameLayout frameLayout_;
    // 定义界面全局管理器
    public LinearLayout llScreen_;
    // 界面上部管理器
    public LinearLayout llUp_;
    // 界面下部管理器
    public LinearLayout llDown_;
    public TabBar tabBar_;       // 界面中部框架
    public TitleBar titleBar_;   // 标题栏
    public StatusBar statusBar_; // 底部状态栏
    MotionEvent motionevent_; // 用户动作事件
    public ProgressDialog progressdialog_; // 进度加载框

    // to store the invisible ViewGroup.
    public HashMap<String, ArrayList<Component>> invisibleViews_;// 保存不显示的div
    // to store the invisible ViewGroup CSS style.
    public HashMap<String, CssStyle> invisibleStyles_;
    // to store the Content layout when switch in them.
    protected Stack<View> stackContentLayout_;
    // to store the content layout has been created. It should be deleted with
    // stackContentLayout_.
    protected HashMap<String, LinearLayout> invisibleLayout_;
    // 界面控件集合,遍历联动时调用
    public Vector<Object> vWidgetArray_;
    /**当前页面的所有component集合*/
    public List<Component> cmpList_;
    Vector<Object> vWidgetArrayTemp_;
    // to store the page 'jpcx'.
    public ContentLayout jpcx_ = null;
    protected HashMap<String, ArrayList<Component>> invisibleViewsTemp_;
    protected HashMap<String, CssStyle> invisibleStylesTemp_;
    // 程序是否进入了后台
    private static boolean isGotoResume_ = false;
    private static boolean isGotoPause_ = false;
	public boolean isShouye_; // 是否首页
	// 是否是单独更新table的流程
	public static boolean updateTable_ = false;
	public static boolean ttimerIscannel_ = true;
	public static boolean timerIsRunning_;
	public static String wantToUpdateTable_ = "1";//这个变量是用来让用户去控制是否自动刷新table的。1：自动更新；0：不要自动更新
	public static String url;
	public static boolean istimeout_ = false;
	public static String phonenum_ = null;
	/** Global lock for APP extended widgets. */
	public static final Object UI_LOCK = new Object();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化菜单命令对应表
        hashMenu_ = new Hashtable<String, String>();
    }
    
    protected void onResume() {
        super.onResume();
        isGotoResume_ = true;
        isGotoPause_ = false;
        CHANGEWORKED = true;
    }

    /**
	 * Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). 
	 * */
    protected void onPause() {
        super.onPause();
        isGotoPause_ = true;
        if (null != exitAppTimer_){
        	exitAppTimer_.cancel();
        	exitAppTimer_ = null;
        }
        isGotoResume_ = false;
        HIDESCREEN = getClass().toString();
    }

    /**
	 * Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity. 
	 * */
	protected void onStop () {
		super.onStop();
		if(mid_ == null || mid_.um_ == null){
			return;
		}
		if (isGotoPause_ && !isGotoResume_ && mid_.um_.loginStatus_ != null && !mid_.um_.loginStatus_.equals("0")) {
			if (exitAppTimer_ == null) {
				exitAppTimer_ = new Timer();
			}
			exitAppTimer_.schedule(new TimerTask() {
				public void run() {
					if (!isGotoResume_) {
						exitApplication();
					}
				}

			}, 60000);
		}
		
		if (isGotoResume_ && null != progressdialog_) {
			progressdialog_.dismiss();
			progressdialog_ = null;
		}
	}
	
	/**
	 * 结束所有的activity，完全退出应用
	 * */
	public void exitApplication() {
		for (Activity act : activities_) {
			act.finish();// 显式结束
		}
		finish();
		System.exit(0);
	}


    public void onCreateSelectDialog(BaseView bv, View ll) {
        Dialog dlg = new Dialog(this, R.style.dialog);
        dlg.setContentView(ll);
        dlg.setCancelable(false);
        // 设置dialog位置
        Window mWindow = dlg.getWindow();
        // 使对话框位于屏幕的底部并居中
        mWindow.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
        // 使对话框二边没有空隙
        mWindow.setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (!isFinishing())
            dlg.show();
        SelectView.selectV.ad_ = dlg;
    }

    public void onCreateProgressDialog(BaseView bv, Task task, String content) {
        progressdialog_ = new ProgressDialog(this, R.style.dialog, task, content);
        // 设置dialog位置
        Window mWindow = progressdialog_.getWindow();
        // 使对话框位于屏幕居中
        mWindow.setGravity(Gravity.CENTER);
        // 使对话框适应子元素大小
        mWindow.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (!bv.isFinishing())
            progressdialog_.show();
    }


    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        // 得到中层管理框架中的域数量
        ArrayList<View> cmps = new ArrayList<View>();
        traversingComponents(tabBar_.getContentLayout(), cmps);
    }

    /**
     * Return maximum width of text in item list.
     */
    public int preferredItemTextWidth() {
        int ITEM_LEFT_MARGIN = 7;
        int SCROLL_BAR_WIDTH = 4;
        int SCROLL_BAR_RIGHT_MARGIN = 2;
        return (Utils.screenWidth_ - ITEM_LEFT_MARGIN - (showVerticalScrollBar_ ? (SCROLL_BAR_WIDTH + SCROLL_BAR_RIGHT_MARGIN)
                : 0));
    }

    /**
     * add a component and init its left_/top_ auto.
     */
    public int append(View c) {
        // if (itemV_ == null)
        // itemV_ = new Vector();
        // itemV_.addElement(c);
        // return itemV_.size() - 1;
        return -1;
    }

    // add a component
    public void appendAtFixP(View c) {
        try {
            ((Component) c).mould();// 计算大小 把控件定型
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        if (updateTable_) {//局部更新view
			if (!ttimerIscannel_) {
				int childCount = tabBar_.getContentChildCount();
				String cClassStr = c.getClass().toString();
				for (int i = 0; i < childCount; i++) {
					View v = tabBar_.getContentChild(i);
					if (cClassStr.equals(v.getClass().toString())) {
						if (c instanceof Div) {
							if (((Div) c).name_ != null && ((Div) c).name_ != null 
									&&((Div) v).name_.equals(((Div) c).name_)) {
								tabBar_.removeContentChild(i);
								tabBar_.addContentChild(c, i);
								break;
							}
						} else if (c instanceof Table) {
							if (((Table) v).attrName_.equals(((Table) c).attrName_)) {
								tabBar_.removeContentChild(i);
								tabBar_.addContentChild(c, i);
								break;
							}
						} else if (c instanceof RowPanel) {
							//此处对RowPanel里面的view没有做名字的比对，其实是不严谨的，当当前界面有很多个RowPanel时将会出错
							//目前此处只有对label做局部更新，所以先只取第一个Label的名字做比对
							if (((RowPanel) c).getChildCount() == ((RowPanel) v).getChildCount()
									&& ((RowPanel) c).getChildAt(0) instanceof Label
									&& ((RowPanel) v).getChildAt(0) instanceof Label
									&& ((Label)(((RowPanel) c).getChildAt(0))).attrName_ != null
									&& ((Label)(((RowPanel) v).getChildAt(0))).attrName_ != null
									&& ((Label)(((RowPanel) c).getChildAt(0))).attrName_.equals(((Label)(((RowPanel) v).getChildAt(0))).attrName_)) {
								tabBar_.removeContentChild(i);
								tabBar_.addContentChild(c, i);
								break;
							}
						}
					} else if (v instanceof FormLayout) {
						for (int f = ((FormLayout)v).getChildCount() - 1; f >= 0; f--) {
							View vv = ((FormLayout)v).getChildAt(f);
							if (cClassStr.equals(vv.getClass().toString())) {
								if (c instanceof Table) {
									if (((Table) vv).attrName_.equals(((Table) c).attrName_)) {
										((FormLayout)v).removeViewAt(f);
										((FormLayout)v).addView(c, f);
										break;
									}
								}
							}
						}
					}
				}
			}
            timerIsRunning_ = false;
        }  else if (Table.isUpdateTable_ != -1) {
            tabBar_.addContentChild(c, Table.isUpdateTable_);
        } else {
            if (null != tabBar_)
            tabBar_.addContentChild(c);
         // 将控件添加至联动控件集合
            vWidgetArray_.add(c);
        }
        
    }

    public void changeDateViewsStepByStep(View v) {
        if (v == null) {
            return;
        }
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            int size = vg.getChildCount();
            for (int i = 0; i < size; i++) {
                changeDateViewsStepByStep(vg.getChildAt(i));
            }
        } else if (v instanceof Radio) {
            Radio radio = (Radio) v;
            if (radio.sortKey_.toLowerCase().equals("sortprice")) {
                radio.setCheckedManually(true);
            }
        } 
    }

    public FormAction getFormByComponent(View c) {
        if (formV_ != null && c != null) {
            for (int i = 0; i < formV_.size(); i++) {
                FormAction f = (FormAction) formV_.elementAt(i);
                if (f.isInFormAction(c))
                    return f;
            }
        }
        return null;
    }

    // 隐藏界面状态栏
    void hideSystemBar(Activity activity) {
        // 隐藏android系统定义的标题栏
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    // 初始化界面框架管理器
    // 将界面大致分为上中下三部分 titlebar(返回，首页) tabbar(切换)
    protected void initScreenManager(Activity activity) {
        // 初始化界面最上层控件
        frameLayout_ = new FrameLayout(activity);
        frameLayout_.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
        // 初始化界面背景域
        ivBackground_ = new ImageView(activity);
        // 设置图片背景域的缩放类型为不缩放。由于添加到FrameLayout以后，默认的会对图片域进行缩放，无法全屏显示，所以应设置一个缩放参数
        ivBackground_.setScaleType(ImageView.ScaleType.CENTER);
        // 初始化界面整体框架管理器
        llScreen_ = new LinearLayout(activity);
        // 初始化界面上部框架管理器
        llUp_ = new LinearLayout(activity);
        // 初始化TabBar控件
        tabBar_ = new TabBar(activity);
        // 初始化界面下部框架管理器
        llDown_ = new LinearLayout(activity);
        // 将界面整体框架管理器布局设置为垂直向布局
        llScreen_.setOrientation(LinearLayout.VERTICAL);
        // 将界面上部框架管理器布局设置为垂直向布局
        llUp_.setOrientation(LinearLayout.VERTICAL);
        // 设置滑动域权重值大于零，使下部框架能够紧靠界面最下方，类似于传统状态栏效果。
        tabBar_.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1));
        // 设置tabbar子元素的布局方式为垂直布局
        tabBar_.setOrientation(LinearLayout.VERTICAL);
        // 将界面下部框架管理器布局设置为垂直向布局
        llDown_.setOrientation(LinearLayout.VERTICAL);
        llDown_.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        initActionList(activity);
        addBackground(activity);
        hideSystemBar(activity);
    }

    // 初始化联动控件集合
    private void initActionList(Activity activity) {
        vWidgetArray_ = null;
        vWidgetArray_ = new Vector<Object>();
        cmpList_ = null;
        cmpList_ = new ArrayList<Component>();
    }

    private void addBackground(Activity activity) {
        // 添加背景图片
        frameLayout_.addView(ivBackground_);
        // 添加界面功能控件总管理器
        frameLayout_.addView(llScreen_);
    }

    public void show(final Activity activity) {
        // 设置llScreen中的子元素水平、垂直居中
        if (!activity.isFinishing()) {
            activity.runOnUiThread(new Runnable() {

                public void run() {
                    // 在重新添加界面元素前,先将以前的元素框架全部清空,保证在切换界面的时候不会出现空屏的情况
                    if (null != llScreen_) {
                        llScreen_.removeAllViews();
                        llScreen_.setGravity(Gravity.CENTER);
                        // 将界面上部框架添加至界面整体框架
                        llScreen_.addView(llUp_);
                        // 设置界面中部框架子元素对其方式
                        tabBar_.setGravity(Gravity.CENTER);
                        // 将界面中部框架添加至界面整体框架
                        llScreen_.addView(tabBar_);
                        // 将界面下部框架添加至界面整体框架
                        llScreen_.addView(llDown_);
                    }
                    // 将界面整体框架设置为可显示内容
                    if (null != activity && null != frameLayout_)
                        activity.setContentView(frameLayout_);
                }

            });
        }
    }

    void setComponentLister(ComponentListener listener) {
        listener_ = listener;
    }

    FormAction getHiddenFormByName(String name) {
        if (formV_ != null) {
            for (int i = 0; i < formV_.size(); i++) {
                FormAction fa = (FormAction) formV_.elementAt(i);
                if (name != null && name.equals(fa.name_) && fa.isHidden_)
                    return fa;
            }
        }
        return null;
    }

    public void addTitleBar() {
        if (titleBar_ == null) {
            titleBar_ = new TitleBar(this);
            titleBar_.setWidth(Utils.screenWidth_);
        }
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (llUp_ != null && llUp_.getChildCount() == 0 && titleBar_ != null)
                    llUp_.addView(titleBar_);
            }

        });
    }


    void removeTabBar() {
        if (tabBar_ != null) {
            itemStartH_ = tabBar_.getTop();
        }
    }

    public void addForm(FormAction fa) {
        if (formV_ == null)
            formV_ = new Vector<FormAction>();
        formV_.addElement(fa);
    }

    /**
     * Default height to get an image.
     */
    public final int preferredImageHeight() {
        Paint paint = new Paint();
        paint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        paint.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
        int ITEM_MARGIN = 2;
        return (int) (6 * paint.getTextSize() + 2 * ITEM_MARGIN);
    }

    /**
     * Default width to get an image.
     */
    public final int preferredImageWidth() {
        return 3 * Utils.screenWidth_ / 4;
    }

    /** get select radio by groupName_ */
    Radio getSelectRadio(BaseView parent, Radio temp) {
        String groupName = temp.groupName_;
        synchronized (UI_LOCK) {
            int sz = tabBar_.getContentChildCount();
            for (int i = 0; i < sz; ++i) {
                View c = (View) tabBar_.getContentChild(i);
                if (c instanceof Radio) {
                    Radio r = (Radio) c;
                    if (r.groupName_ != null && r.groupName_.equals(groupName) && r.isChecked())
                        return r;
                } else if (c instanceof Table) {
                    Table table = (Table) c;
                    for (int j = 0; j < table.cells_.size(); j++) {
                        Table.Cell cell = (Table.Cell) table.cells_.elementAt(j);
                        for (int k = 0; k < cell.size(); k++) {
                            View tbcmp = (View) cell.elementAt(k);
                            if (tbcmp instanceof Radio) {
                                Radio tbrd = (Radio) tbcmp;
                                if (tbrd.groupName_ != null && tbrd.groupName_.equals(groupName) && tbrd.isChecked())
                                    return tbrd;
                            }
                        }
                    }
                } else if (c instanceof SegmentLinearLayout) {
                    SegmentLinearLayout sll = (SegmentLinearLayout) c;
                    int size = sll.getChildCount();
                    for (int j = 0; j < size; j++) {
                        Radio radio = (Radio) sll.getChildAt(j);
                        if (radio.groupName_ != null && radio.groupName_.equals(groupName) && radio.isChecked())
                            return radio;
                    }
                }
            }
        }
        return null;
    }

    public static int getBottomMenuBarButtonHeight() {
        return BaseView.DEFAULT_PAINT_SIZE;
    }

    final void setRightMenuMode(int mode, String text) {
        synchronized (UI_LOCK) {
            rightMenuMode_ = mode;
            if (rightMenuMode_ == OPTIONS_MENU) {
                rightMenuText_ = getString(R.string.menu);
            } else if (rightMenuMode_ == OTHER_MENU) {
                rightMenuText_ = text;
            } else {
                rightMenuText_ = null;
            }
        }
    }

    final void setLeftMenuMode(int mode) {
        synchronized (UI_LOCK) {
            leftMenuMode_ = mode;
            if (leftMenuMode_ == BACK_MENU)
                leftMenuText_ = getString(R.string.menuback);
            else if (leftMenuMode_ == EXIT_MENU)
                leftMenuText_ = getString(R.string.menuExit);
            else
                leftMenuText_ = null;
        }
    }

    /**
     * When we go back we should re-set current item to be the current channel.
     */
    public void keyBackPressed() {
    	
    }

    /**
     * This is triggered when the right soft key is pressed (the left key is always bound to "back", but allow derived
     * classes to override this.
     */
    void keyActionSoftKey() {
    }


    void removeCountLabel() {
        if (countTimer_ != null) {
            countTimer_.cancel();
            countTimer_ = null;
            countLabel_ = null;
        }
    }

    /**
     * remove all component.
     */
    public void removeAll() {
        // 清除tabBar域详细内容管理器中的所有控件
        tabBar_.removeAllContentChild();
        // removeAllComponents();
    }

    void populateImpl() {
    }

    public void dealWithLink(String link, BaseView bv,Boolean bl) {
        try {
            mid_.dialWeb(link, bv);
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
    }

    protected Dialog onCreateDialog() {
        // TODO Auto-generated method stub
        return null;
    }


    /**
     * Adjusts the view port to fit the screen and high-light component.
     * 
     * @param keyCode
     * @param pos
     *            The particular position which is need to be in the screen.
     */
    void adjustViewPort(int keyCode, int pos) {
        boolean isAdjust = false;
        if (pos <= 0)
            return;
        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_UP:
            if (pos < viewport_[TOP]) {
                viewport_[TOP] = pos;
                viewport_[BOTTOM] = viewport_[TOP] + viewport_[HEIGHT];
                isAdjust = true;
            }
            break;
        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (pos > viewport_[BOTTOM]) {
                viewport_[BOTTOM] = pos;
                viewport_[TOP] = viewport_[BOTTOM] - viewport_[HEIGHT];
                isAdjust = true;
            }
            break;
        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (pos < viewport_[VIEW_LEFT]) {
                viewport_[VIEW_LEFT] = pos;
                viewport_[VIEW_RIGHT] = viewport_[VIEW_LEFT] + viewport_[WIDTH];
                isAdjust = true;
            }
            break;
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (pos > viewport_[VIEW_RIGHT]) {
                viewport_[VIEW_RIGHT] = pos;
                viewport_[VIEW_LEFT] = viewport_[VIEW_RIGHT] - viewport_[WIDTH];
                isAdjust = true;
            }
            break;
        default:
            break;
        }
        if (isAdjust)
            llScreen_.invalidate();
    }

    /**
     * 当横竖屏切换时调用此方法交换屏幕宽高
     * 
     * @param roientation
     *            int 横竖屏标志
     * */
    protected void changeScreenWidthHeight(int roientation) {
        Utils.printOutToConsole("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!roientation = " + roientation);
        if (roientation == Configuration.ORIENTATION_LANDSCAPE && Utils.screenHeight_ > Utils.screenWidth_) {
            // 横屏。交换 screenHeight_ 和 screenWidht_ 的值。
            Utils.screenHeight_ = Utils.screenHeight_ + Utils.screenWidth_;
            Utils.screenWidth_ = Utils.screenHeight_ - Utils.screenWidth_;
            Utils.screenHeight_ = Utils.screenHeight_ - Utils.screenWidth_;
        } else if (roientation == Configuration.ORIENTATION_PORTRAIT && Utils.screenHeight_ < Utils.screenWidth_) {
            // 竖屏。再交换 screenHeight_ 和 screenWidht_ 的值，回复原值。
            Utils.screenHeight_ = Utils.screenHeight_ + Utils.screenWidth_;
            Utils.screenWidth_ = Utils.screenHeight_ - Utils.screenWidth_;
            Utils.screenHeight_ = Utils.screenHeight_ - Utils.screenWidth_;
        }
    }

    public void stopTicker() {
        if (StringTicker.instance_ != null)
            StringTicker.instance_.pauseTicker();
    }

    /**
     * @param div
     * @param cssStyle
     */
    public void appendInvisible(Div div) {
        if (div == null) {
            return;
        }
        if (invisibleViews_ == null) {
            invisibleViews_ = new HashMap<String, ArrayList<Component>>();
        }
        if (invisibleStyles_ == null) {
            invisibleStyles_ = new HashMap<String, CssStyle>();
        }
        int size = div.childrenAmount();
        if (size <= 0) {
            return;
        }
        ArrayList<Component> views = new ArrayList<Component>();
        for (int i = 0; i < size; i++) {
            try {
                views.add(div.child(i));
            } catch (Exception e) {
                continue;
            }
        }
        invisibleViews_.put(div.name_, views);
        invisibleStyles_.put(div.name_, div.cssStyle_);
    }

    /**
     * Use the layout to replace the current view in the middle panel.
     * 
     * @param newLayout
     * @param restoreCurrentLayout
     *            if the old layout should be restored or not.
     */
    final void resetMiddlePanel(View neoLayout, boolean restoreCurrentLayout) {
        try {
            if (tabBar_ == null || neoLayout == null) {
                return;
            }
            if (restoreCurrentLayout) {
                View view = tabBar_.getContentLayout();
                pushContentStack(view);
            }
            tabBar_.replaceContentView((ContentLayout) neoLayout);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    /**
     * @param view
     */
    protected void pushContentStack(View view) {
        try {
            if (stackContentLayout_ == null) {
                stackContentLayout_ = new Stack<View>();
            }
            stackContentLayout_.push(view);
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }
    }

    /**
     * @return
     */
    protected final View popContentStack() {
        try {
            if (stackContentLayout_ == null) {
                return null;
            } else
                return stackContentLayout_.pop();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @return
     */
    protected final boolean isContentStackEmpty() {
        try {
            if (stackContentLayout_ == null) {
                return true;
            } else
                return stackContentLayout_.isEmpty();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 
     */
    public final void delContentStack() {
        if (stackContentLayout_ != null) {
            final int size = stackContentLayout_.size();
            for (int i = 0; i < size; i++) {
                View view = stackContentLayout_.elementAt(i);
                Utils.releaseResource(view);
                if (view instanceof LinearLayout) {
                    ((LinearLayout) view).removeAllViews();
                } else if (view instanceof RelativeLayout) {
                    ((RelativeLayout) view).removeAllViews();
                }
            }
        }
        stackContentLayout_ = null;
        if (invisibleLayout_ != null) {
            java.util.Collection<LinearLayout> c = invisibleLayout_.values();
            Iterator<LinearLayout> it = c.iterator();
            while (it.hasNext()) {
                LinearLayout layout = (LinearLayout) it.next();
                Utils.releaseResource(layout);
                layout.removeAllViews();
            }
            invisibleLayout_.clear();
        }
        invisibleLayout_ = null;
    }

    /**
     * Create the local invisible ViewGroup. If the accessory is null, no layout will be created.
     * 
     * @param accessory
     * @return
     */
    protected final TabBar.ContentLayout createLocalLayout(String accessory, BaseView activity) {
        TabBar.ContentLayout layout = null;
        if (invisibleViews_ == null) {
            return null;
        }
        if (accessory == null) {
            return null;
        }
        // get the destination ViewGroup name.
        String destDivName = accessory.substring(accessory.indexOf("://") + "://".length());
        // avoid reCreating if the layout is existing.
        if (invisibleLayout_ != null) {
            layout = (ContentLayout) invisibleLayout_.get(destDivName);
        }
        if (layout != null) {
            return layout;
        }
        // search the destination ViewGroup.
        try {
            ArrayList<Component> views = null;
            // find all views in the layout.
            views = invisibleViews_.get(destDivName);
            if (views == null) {
                return null;
            }
            layout = TabBar.createContentLayout(activity);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.name_ = destDivName;
            // apply CSS style of this layout.
            CssStyle layoutCss = invisibleStyles_.get(destDivName);
            // LPParseHtml.applyCssOnLayout(layout, layoutCss);
            layout.setCssStyle(layoutCss);
            layout.mould();
            // append views into this layout.
            appendChildIntoLayout(this, layout, views, 0);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        if (layout != null) {
            if (invisibleLayout_ == null) {
                invisibleLayout_ = new HashMap<String, LinearLayout>();
            }
            invisibleLayout_.put(destDivName, layout);
        }

        return layout;
    }

    /**
     * look for table by its name.
     * 
     * @param bv
     * @param tableName
     * @return
     */
    protected static Table findTable(BaseView bv, String tableName) {
        if (bv == null || tableName == null) {
            return null;
        }
        Table table = null;
        try {
            ArrayList<View> cmps = new ArrayList<View>();
            traversingComponents(bv.tabBar_.getContentLayout(), cmps);
            for (View view : cmps) {
                if (view instanceof Table) {
                    Table tb = (Table) view;
                    if (tb.attrName_.equals(tableName)) {
                        table = tb;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
        }

        return table;
    }

    /**
     * @param view
     * @return
     */
    public static final Table searchTableInSameDiv(View view) {
        Table table = null;
        try {
            ViewGroup vg = searchRealParent(view);
            table = findTable(vg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        return table;
    }

    /**
     * @param vg
     * @return
     */
    private static Table findTable(View view) {
        Table table = null;
        if (view == null) {
            return null;
        }
        if (view instanceof Table) {
            return (Table) view;
        } else if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            int size = vg.getChildCount();
            for (int i = 0; i < size; i++) {
                table = findTable(vg.getChildAt(i));
                if (table != null) {
                    break;
                }
            }
        }
        return table;
    }

    private static final ViewGroup searchRealParent(View view) {
        ViewGroup vg = null;
        try {
            ViewParent parent = view.getParent();
            if (!(parent instanceof ViewGroup)) {
                return null;
            }
            vg = (ViewGroup) parent;
            if (parent instanceof SelfLayout || parent instanceof RowPanel) {
                vg = searchRealParent(vg);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        return vg;
    }

    /**
     * @param srcView
     * @param cmps
     */
    public static final void traversingComponents(View srcView, ArrayList<View> cmps) {
        if (srcView == null || cmps == null) {
            return;
        }
        cmps.add(srcView);
        if (srcView instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) srcView;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View childView = vg.getChildAt(i);
                if (childView instanceof ViewGroup) {
                    traversingComponents((ViewGroup) childView, cmps);
                } else {
                    cmps.add(childView);
                }
            }
        }
    }

    public void refresh() {
        this.runOnUiThread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                if (null != titleBar_)
                    titleBar_.invalidate();
                tabBar_.invalidate();
            }
        });
    }


    /** 解析完之后控件的排版 */
    public void appendComponents(List<Component> cmps) {
        if (cmps == null || cmps.size() < 1) {
            return;
        }

        try {
            RowPanel rp = null;
            for (Component c : cmps) {
                if (c == null) {
                    continue;
                }
                if (c instanceof Panel) {// LPPanel的控件 单独占一行 可以包含其他控件
                    if (rp != null) {
                        appendAtFixP(rp);
                    }
                    rp = null;
                    ((Panel) c).loadAllChildren();
                    appendAtFixP(c.getCmpView());
                } else {
                    if (c instanceof Wrap) {
                        if (rp != null) {
                            appendAtFixP(rp);
                        }
                        rp = null;
                    } else {
                        if (rp == null) {
                            rp = new RowPanel(this);
                        }
                        rp.addView(c.getCmpView());
                    }
                }
            }
            if (rp != null) {
                appendAtFixP(rp);
            }
            rp = null;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
        // 复位llV_的显示起始坐标 如果试局部更新，则不执行此操作
        if (!updateTable_) {
        	tabBar_.scrollDown_.scrollTo(0, 0);
        }
        
        runOnUiThread(new Runnable() {
            public void run() {
                resetAllViewLayout();
            }
        });

    }

    private void resetAllViewLayout() {

        // 得到llV_下子的个数
        int llvCC = tabBar_.llV_.getChildCount();
        // 保存需要重置Layout的div
        Div llt = null;
        // 保存需要重置layout的scrollView
        LPLinearLayoutView lplv = null;
        // 保存llt里面的两个table
        Table[] table = null;
        // 保存需要重置layout的SelfLayout
        SelfLayout sl = null;
        // 保存llv里子的总高
        int selfLayoutH = 0;
        // 一屏中显示llv的高
        int llvCanSeeH = 0;
        if (null != llScreen_)
            llvCanSeeH = llScreen_.getHeight();
        if (null != titleBar_)
            llvCanSeeH = llvCanSeeH - titleBar_.height_;

        for (int i = 0; i < llvCC; i++) {
            View v = (View) tabBar_.llV_.getChildAt(i);
            if (v instanceof Div) {
                Div lll = (Div) v;
                if (lll.strHeight_ != null && lll.strHeight_.equals("100%")) {
                    llt = lll;
                    int tc = lll.getChildCount();
                    table = new Table[tc];
                    for (int n = tc - 1; n >= 0; n--) {
                        View vi = lll.getChildAt(n);
                        if (vi instanceof LPLinearLayoutView) {
                            lplv = (LPLinearLayoutView) vi;
                        } else if (vi instanceof Table) {
                            table[n] = (Table) vi;
                        }
                    }
                }
            } else if (v instanceof SelfLayout) {
                sl = (SelfLayout) v;
                selfLayoutH = sl.getRealHeight();
            }
        }

        if (llt != null) {

            if (llvCanSeeH - selfLayoutH > 0) {
                LayoutParams params = (LayoutParams) llt.getLayoutParams();
                if (params != null) {
                    llt.height_ = (llvCanSeeH - selfLayoutH);
                    params.height = llt.height_;
                    llt.setLayoutParams(params);
                }

                if (lplv != null) {
                    LayoutParams lp = (LayoutParams) lplv.getLayoutParams();
                    if (lp != null) {
                        lp.height = llt.height_ - table[0].height_;
                        lplv.sHeight_ = lp.height;
                        lplv.setLayoutParams(lp);
                    }
                }
                if (table[1] != null) {
                    LayoutParams lp = (LayoutParams) table[1].getLayoutParams();
                    if (lp != null) {
                        lp.height = llt.height_ - table[0].height_;
                        table[1].setLayoutParams(lp);
                        table[1].height_ = lp.height;
                    } else {
                        lp = new LayoutParams(table[1].width_, llt.height_ - table[0].height_);
                        table[1].height_ = lp.height;
                    }
                }
            }
        }
    }

    /**
     * @param cx
     * @param vg
     * @param cmps
     */
    public static void appendChildIntoLayout(Context cx, ViewGroup vg, ArrayList<Component> cmps, int firstColWidth) {
        try {
            RowPanel rp = null;
            int loop = 0;
            while (loop < cmps.size()) {
                Component c = cmps.get(loop);
                if (c == null) {
                    continue;
                }
                if (c instanceof Panel) {
                    appendRowLayout(vg, rp);
                    rp = null;
                    ((Panel) c).loadAllChildren();
                    vg.addView(c.getCmpView());
                } else {
                    if (c instanceof Wrap) {
                        appendRowLayout(vg, rp);
                        rp = null;
                    } else {
                        try {
                            if (c instanceof Label) {
                            	if (Table.firstColWidth_ > 0 || firstColWidth > 0) {
                            		//解决当有两个td时的换行问题 且第二个td超宽时此table无法隐藏，导致联动失败
//                            		((LPLabel) c).offsetLength = firstColWidth + LPTable.firstColWidth_ + 20;
                            		((Label) c).offsetLength = Math.max(firstColWidth, Table.firstColWidth_) + Utils.getSystemScaledValue(20);
                            	}
                                c.mould();
                                ((Label) c).removeSelfLayout();
                            }
                            if (c instanceof Select) {
                            	if (Table.firstColWidth_ > 0 || firstColWidth > 0) {
                            		//兼容select控件超宽问题
                            		((Select) c).offsetLength = firstColWidth + Table.firstColWidth_ + Utils.getSystemScaledValue(20);
                            	}
                                
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            Utils.printException(e);
                        }
                        if (rp == null) {
                            rp = new RowPanel(cx);
                        }
                        
                        rp.addView(c.getCmpView());
                        insertWrap(cmps, c);
                    }
                }
                loop++;
            }
            appendRowLayout(vg, rp);
            rp = null;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    static void insertWrap(ArrayList<Component> cmps, Component c) {
        if (c instanceof Label) {
            try {
                if (c.getCmpWidth() >= Component.MAX_ROW_WIDTH - 10) {
                    int index = cmps.indexOf(c);
                    cmps.add(index + 1, new Wrap());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Utils.printException(e);
            }
        }
    }

    /**
     * @param vg
     * @param rp
     */
    private static void appendRowLayout(ViewGroup vg, RowPanel rp) {
        try {
            if (rp != null) {
                if (vg instanceof Cell.CellLayout) {
                    rp.setInTable(true);
                }
                // if (rp.getChildCount() > 1) {
                vg.addView(rp);
                // } else if (rp.getChildCount() == 1) {
                // View v = rp.getChildAt(0);
                // rp.removeAllViews();
                // vg.addView(v);
                // }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    public static void setTypeFace(TextPaint font, String string) {
        if (font == null) {
            return;
        }
        font.setTypeface(getTypeFace(string));
        if (string != null) {
            font.setFakeBoldText(getFontType(string));
        }
    }

    /**
     * 设置字体是否粗体
     * */
    private static boolean getFontType(String string) {
        if (string.equalsIgnoreCase("bold")) {
            return true;
        } else {
            return false;
        }
    }

    public static Typeface getTypeFace(String string) {
        Typeface tface = null;
        try {
            if (string.equalsIgnoreCase("bold")) {
                tface = Typeface.defaultFromStyle(Typeface.BOLD);
            } else if (string.equalsIgnoreCase("normal")) {
                tface = Typeface.defaultFromStyle(Typeface.NORMAL);
            } else {
                tface = null;
            }
        } catch (Exception e) {
            tface = null;
        }
        return tface;
    }

    /*************************************************************************
     * These methods must be moved into Component after it becomes Class.
     *************************************************************************/
    /**
     * @param layout
     */
    public static LinearLayout createSelfLayout(Context context, LinearLayout.LayoutParams layout, CssStyle cs,
            View self) {
        if (context == null || layout == null || cs == null) {
            return null;
        }
        LinearLayout rightLayout = null;
        LinearLayout bottomLayout = null;
        if (cs.left_ != Integer.MIN_VALUE) {
            layout.leftMargin = cs.left_;
        } else if (cs.right_ != Integer.MIN_VALUE) {
            layout.rightMargin = cs.right_;
            rightLayout = BaseView.createRightLayout(context);
        }
        if (cs.top_ != Integer.MIN_VALUE) {
            layout.topMargin = 0;
        } else if (cs.bottom_ != Integer.MIN_VALUE) {
            bottomLayout = BaseView.createBottomLayout(context);
        }
        if (rightLayout != null) {
            rightLayout.addView(self);
        }
        if (bottomLayout != null) {
            if (rightLayout != null) {
                bottomLayout.addView(rightLayout);
            } else {
                bottomLayout.addView(self);
            }
        }

        if (bottomLayout != null) {
            return bottomLayout;
        } else {
            return rightLayout;
        }

    }

    /**
     * @return
     */
    public static LinearLayout createRightLayout(Context context) {
        LinearLayout layout = new Component.SelfLayout(context);
        layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        layout.setGravity(Gravity.RIGHT);
        return layout;
    }

    /**
     * @return
     */
    public static LinearLayout createBottomLayout(Context context) {
        LinearLayout layout = new Component.SelfLayout(context);
        layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
        layout.setGravity(Gravity.BOTTOM);
        return layout;
    }

    /**
     * @param v
     */
    public static void removeViewsStepByStep(View v, View ignoreView) {
        if (v == null || v == ignoreView) {
            return;
        }
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            int size = vg.getChildCount();
            for (int i = 0; i < size; i++) {
                removeViewsStepByStep(vg.getChildAt(i), ignoreView);
            }
            vg.removeAllViews();
        }
    }

    public static void setComponentTopMargin(Component c) {
        try {
            CssStyle cs = c.getCssStyle();
            View v = c.getCmpView();
            if (null == v || v instanceof SelfLayout || v instanceof FormLayout) {
                return;
            }
            LinearLayout.LayoutParams lp = (LayoutParams) v.getLayoutParams();
            if (null != lp && cs != null && cs.top_ != Integer.MIN_VALUE) {
                if (cs.top_ == 0) {
                    lp.topMargin = 0;
                } else {
                    lp.topMargin = BaseView.DEFAULT_VIEW_TOP_MARGIN;
                }
			} else if (null != lp && !c.isInTable()) {
				lp.topMargin = BaseView.DEFAULT_VIEW_TOP_MARGIN;
				if (c instanceof RowPanel) {
					RowPanel lprp = (RowPanel) c;
					View temp = lprp.getChildAt(0);
					if (temp instanceof mViewFlipper) {
						lp.topMargin = 0;
					}
				}
			}
            if (v  instanceof Table){
            	Table table = (Table) v;
            	if (table.isfull_){
            		lp.topMargin = 0;
            	}
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }

    private void relreaseBackgroundBitmap (int viewIndex) {
    	switch (viewIndex) {
    	case 1:
    		if (ivMainViewAndDetailViewBackgroundBitmap_ != null) {
    			ivMainViewAndDetailViewBackgroundBitmap_.isRecycled();
    			ivMainViewAndDetailViewBackgroundBitmap_ = null;
    		}

    		break;
    	case 2:
    	case 3:
    		if (ivLoginViewBackgroundBitmap_ != null) {
    			ivLoginViewBackgroundBitmap_.isRecycled();
    			ivLoginViewBackgroundBitmap_ = null;
    		}
    		break;
    	}
    	System.gc();
    }
    
    /**
     * 设置界面的背景图片
     * 
     * @param resourceId
     *            背景图片资源ID
     * @param bv
     *            界面对象
     * @param viewIndex 标识在哪个界面 1:LoginView; 2:MainView; 3:DetailView
     */
    public void setBackgroundResource(int resourceId, BaseView bv, int viewIndex) {
    	relreaseBackgroundBitmap (viewIndex);
    	if (null == ivBackground_)
            ivBackground_ = new ImageView(bv);
    	switch (viewIndex) {
    	case 1:
    		if (ivLoginViewBackgroundBitmap_ == null)
    			ivLoginViewBackgroundBitmap_ = Utils.scaleImage(bv, resourceId, Utils.screenWidth_, Utils.screenHeight_, 1);
	        ivBackground_.setImageBitmap(ivLoginViewBackgroundBitmap_);
	        break;
    	case 2:
    	case 3:
    		if (ivMainViewAndDetailViewBackgroundBitmap_ == null)
    			ivMainViewAndDetailViewBackgroundBitmap_ = Utils.scaleImage(bv, resourceId, Utils.screenWidth_, Utils.screenHeight_, 1);
	        ivBackground_.setImageBitmap(ivMainViewAndDetailViewBackgroundBitmap_);
	        break;
    	}
    }
// 清空资源
    public void dispose() {
        if (invisibleViews_ != null)
            invisibleViews_.clear();
        invisibleViews_ = null;
        if (invisibleStyles_ != null)
            invisibleStyles_.clear();
        invisibleStyles_ = null;

        ivBackground_ = null;
        frameLayout_ = null;
        llScreen_ = null;
        llUp_ = null;
        llDown_ = null;
        motionevent_ = null;
        if (vWidgetArray_ != null)
            vWidgetArray_.removeAllElements();
        vWidgetArray_ = null;
        if (cmpList_ != null) {
			cmpList_.clear();
		}
        cmpList_ = null;
        if (vWidgetArrayTemp_ != null)
            vWidgetArrayTemp_.removeAllElements();
        vWidgetArrayTemp_ = null;
        jpcx_ = null;
        if (invisibleViewsTemp_ != null)
            invisibleViewsTemp_.clear();
        invisibleViewsTemp_ = null;
        if (invisibleStylesTemp_ != null)
            invisibleStylesTemp_.clear();
        invisibleStylesTemp_ = null;

        listener_ = null;
        titleBar_ = null;
        // tabBar_ = null;
        viewport_ = null;
        rightMenuText_ = null;
        leftMenuText_ = null;
        partScreenWait_ = null;

        if (formV_ != null) {
            formV_.removeAllElements();
            formV_ = null;
        }
        hashMenu_.clear();
        countLabel_ = null;
        delContentStack();
    }

    public void releaseResource() {
        // TODO Auto-generated method stub
        if (null != progressdialog_)
            progressdialog_.dismiss();
        progressdialog_ = null;
    }

    void disposeInChangeChannel() {
        if (invisibleViews_ != null)
            invisibleViews_.clear();
        if (invisibleStyles_ != null)
            invisibleStyles_.clear();
        if (vWidgetArray_ != null)
            vWidgetArray_.removeAllElements();
        if (cmpList_ != null) {
			cmpList_.clear();
		}
        if (vWidgetArrayTemp_ != null)
            vWidgetArrayTemp_.removeAllElements();
        jpcx_ = null;
        if (invisibleViewsTemp_ != null)
            invisibleViewsTemp_.clear();
        if (invisibleStylesTemp_ != null)
            invisibleStylesTemp_.clear();
        viewport_ = null;
        rightMenuText_ = null;
        leftMenuText_ = null;
        if (formV_ != null) {
            formV_.removeAllElements();
        }
        hashMenu_.clear();
        countLabel_ = null;
        delContentStack();
    }

    public void hideSoft() {
		// TODO Auto-generated method stub
    	try {
			InputMethodManager im = ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE));
			if(im != null){
				im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			    return;
			}
		} catch (Exception e) {
//			Utils.printException(e);
		}
	}

	public void addViewForScrollDown() {
		try {
			this.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					View v = tabBar_.llV_.getChildAt(tabBar_.llV_
							.getChildCount() - 1);
					if (!(v instanceof TextView)
							|| !"hide".equals(((TextView) v).getTag())) {
						TextView tv1 = new TextView(BaseView.this);
						tv1.setTag("hide");
						tv1.setLayoutParams(new LinearLayout.LayoutParams(30,
								Utils.getSystemScaledValue(160)));
						tabBar_.llV_.addView(tv1);
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
	//屏幕主窗口滚动，使得输入框抬升或者下降 add by chengli
	public void scrollParent(final int h, final boolean show) {
		// TODO Auto-generated method stub
		if (h < 0){
			return;
		}
		try{
			this.runOnUiThread(new Runnable(){
				@Override
				public void run() {
					//使得整个中间主窗口滚动h的距离，正位向上滚动，负为向下滚动
					if(null != tabBar_){
						Utils.LogE("debug", "scroll h = " + h);
						tabBar_.scrollDown_.scrollTo(0, h);
						if (!show) {
							View v = tabBar_.llV_.getChildAt(tabBar_.llV_
									.getChildCount() - 1);
							if ((v instanceof TextView)
									&& "hide".equals(((TextView) v).getTag())) {
								tabBar_.llV_.removeView(v);
							}
						}
					}
					
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
